import React, {useCallback, useEffect, useMemo, useState} from "react"
import {Pageable} from "../../utils/Page";
import {
    createFactory, disableFactory, enableFactory,
    queryFactories,
    QueryFactoriesRequest,
    QueryFactoriesResponse,
    updateFactory
} from "../../apis/FactoriesApi";
import AuthorizationResource from "../../components/AuthorizationResource";
import {Button, ConfigProvider, Form, Input, Table} from "antd";
import {EditOutlined, PlusOutlined} from "@ant-design/icons";
import {
    buildDisableOrEnableColumnProps,
    castFilterValue,
    mergePaginationAndPageable,
    useTableSearchTextColumnProps
} from "../../utils/AntdTableUtils";
import {QueryGoodsResponse} from "../../apis/GoodsApi";
import DataPageLayout from "../../components/DataPageLayout";
import FormDrawer from "../../components/FormDrawer";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import LoadableButton from "../LoadableButton";
import {disableGoodsBrand, enableGoodsBrand} from "../../apis/GoodsBrandsApi";
import {DisableCondition, disableInConditionToDisableInRequest} from "./GoodsPage";

export interface FactoryProps {

}

export interface FactoryFormData {
    name: string
    contact?: string
    address?: string
}

const FactoryPage: React.FC<FactoryProps> = (props) => {
    const [openAddDrawer, setOpenAddDrawer] = useState(false)
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryFactoriesResponse[]>([])
    const [searchNameText, setSearchNameText] = useState<string>()
    const [searchContactText, setSearchContactText] = useState<string>()
    const [searchAddressText, setSearchAddressText] = useState<string>()
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    const [disable,setDisable] = useState<DisableCondition>(["0"])

    const query = useCallback(() => {
        setLoading(true)
        queryFactories({
            name: searchNameText,
            address: searchAddressText,
            contact: searchContactText,
            disable:disableInConditionToDisableInRequest(disable),
        }, pageable).then(response => {
            setTotalElements(response.data.totalElements)
            setData(response.data.content)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), searchNameText,disable])

    const [editGoodsId, setEditingItemId] = useState<number>()
    const editingItem = useMemo(() => {
        return data.find(it => it.id === editGoodsId)
    }, [editGoodsId, data]);

    useEffect(() => {
        query()
    }, [query]);
    let nameSearchProps = useTableSearchTextColumnProps<QueryFactoriesResponse>("name", {
        placeholder: "名称"
    });
    let contactSearchProps = useTableSearchTextColumnProps<QueryFactoriesResponse>("contact", {
        placeholder: "联系方式"
    });
    let addressSearchProps = useTableSearchTextColumnProps<QueryFactoriesResponse>("address", {
        placeholder: "地址"
    });

    function buildFormItems() {
        return <>
            <Form.Item label={"名称"} name="name" rules={[{required: true}]}>
                <Input/>
            </Form.Item>
            <Form.Item label={"地址"} name="address">
                <Input maxLength={50}/>
            </Form.Item>
            <Form.Item label={"联系方式"} name="contact">
                <Input/>
            </Form.Item>
        </>
    }

    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["货品_厂商_新增"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>新增厂商</Button>
        </AuthorizationResource>}>
            <ConfigProvider componentSize={"small"}>
                <Table loading={loading} dataSource={data} rowKey={"id"} pagination={{
                    current: pageable.page,
                    pageSize: pageable.size,
                    total: totalElements,
                }} onChange={(pagination, filters, sorter) => {
                    setSearchNameText(castFilterValue(filters.name))
                    setSearchContactText(castFilterValue(filters.contact))
                    setSearchAddressText(castFilterValue(filters.address))
                    setDisable(filters.disable as any)
                    setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                }} >
                    <Table.Column dataIndex={"name"} title={"名称"} {...nameSearchProps}/>
                    <Table.Column dataIndex={"address"} title={"地址"} {...contactSearchProps}/>
                    <Table.Column dataIndex={"contact"} title={"联系方式"} {...addressSearchProps}/>
                    <Table.Column dataIndex={"goodsAmount"} title={"商品数量"}/>
                    <Table.Column {...buildDisableOrEnableColumnProps(disable)}/>
                    <Table.Column<QueryGoodsResponse> title={"操作"} render={(_, item) => {
                        return <>
                            <AuthorizationResource authorities={["货品_厂商_修改"]}><Button type={"link"}
                                                                                            onClick={() => {
                                                                                                setEditingItemId(item.id)
                                                                                            }}>
                                <EditOutlined/>
                            </Button></AuthorizationResource>
                            {employeeAuthorizationStore.hasAuthority("货品_厂商_修改") && <LoadableButton
                                type={"link"}
                                danger={!item.disable}
                                onClick={async (event) => {
                                    event.stopPropagation()
                                    item.disable ? await enableFactory(item.id) : await disableFactory(item.id)
                                    query()
                                }}>{item.disable ? "启用" : "禁用"}</LoadableButton>}
                        </>
                    }}/>
                </Table>
            </ConfigProvider>
        </DataPageLayout>
        <FormDrawer<FactoryFormData> onClose={() => setOpenAddDrawer(false)}
                                     title={"新增厂商"}
                                     onConfirm={async (values) => {
                                         return createFactory(values).then(() => {
                                             setOpenAddDrawer(false)
                                             query()
                                         })
                                     }}
                                     open={openAddDrawer}>
            {buildFormItems()}
        </FormDrawer>
        <FormDrawer<FactoryFormData> open={!!editingItem} title={"修改厂商"} onClose={() => {
            setEditingItemId(undefined)
        }} onConfirm={async (values) => {
            return updateFactory(editGoodsId!!, values).then(() => {
                query()
                setEditingItemId(undefined)
            })
        }} initialValues={editingItem}>
            {buildFormItems()}
        </FormDrawer>
    </>
}


export default observerDashboardPageWrapper(FactoryPage, "goods/factories", "厂商")
